import md5 from 'md5'
import jwt from 'jsonwebtoken'
import path from 'path';
import { Request } from 'express';

import { KEY } from '../config/conf';
import { LoginOpt } from "../modules/login/types";
import { UserInfo } from '../common/types/common';
/**
 * 对密码进行加密
 * @param str
 */
export const encrypt = (str: string) => md5(str);

/**
 * 生成token
 * @param opt
 */
export const genToken = (payload: LoginOpt) => {
    // expiresIn 单位是秒, 默认是30天 
    return jwt.sign(payload, KEY, { expiresIn: 60 * 60 * 24 * 30 });
};


/**
 * 对token进行解密
 * @param token
 */
export const deToken = (token: string) => {
    let info;
    try {
        info = jwt.verify(token, KEY);
    } catch (e) {
        return false;
    }
    return info;
};

/**
 * 去掉多余的Bearer
 * @param token 
 */
export const resolveToken = (token: string) => token.replace("Bearer ", '')

/**
 * 解析路径
 * @param p
 */
export const resolve = (p: string) => path.resolve(__dirname, p);


/**
 * 去掉左右空格
 * @param str 
 */
export const trimStr = (str: string) => (str + '').trim();

/**
 * 校验用户名和密码
 * @param username
 * @param pass
 */
export const vertifyField = (username: string, pass: string) => {
    if (!username || !pass) {
        return false;
    }
    return true;
};

/**
 * 获取用户信息
 * @param req
 */
export const getUserInfo = (req: Request) => {
    return (req as any).user as UserInfo;
};


/**
 * 校验参数
 * @param v 
 */
export const checkField = (...vs: unknown[]) => {
    // vs只要有一项为空, 返回false
    const len = vs.length;
    for (let i = 0; i < len; i++) {
        if (!vs[i]) return false;
    }

    // vs每一项都不为空, 返回true
    return true;
}

/**
 * 获取[start, end]之间的数字
 * @param start 
 * @param end 
 * @returns 
 */
export const getRandom = (start: number, end: number) => (Math.random() * (end - start + 1) + start)